package com.fingard.dsp.bank.directbank.alipay01;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundTransCommonQueryRequest;
import com.alipay.api.request.AlipayFundTransOrderQueryRequest;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.response.AlipayFundTransCommonQueryResponse;
import com.alipay.api.response.AlipayFundTransOrderQueryResponse;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.alipay01.bean.*;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.text.StringHelper;


/**
 * Created by F on 2019/5/30.
 */
public class ALIPAY01SinglePay extends DirectBase implements ISinglePay {
    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail retAtsSglDetail;
        if ("190802".equals(p_req1908.reqHeader.commandCode)) {
            retAtsSglDetail = d_190802(p_req1908);
        } else {
            retAtsSglDetail = d_1908(p_req1908);
        }
        retAts.writeRetDetail(retAtsSglDetail);
        return retAts;
    }

    private RetAtsSglDetail d_1908(ReqSingle p_req1908) {
        RetAtsSglDetail retAtsSglDetail = new RetAtsSglDetail();
        try {
            ActSetItem actItem = getBankConfig().getActSetItemByAny(p_req1908.singleDetail.payAct, "", "", "singlePay");
            if (actItem != null) {
                AlipayClient alipayClient = new DefaultAlipayClient(bankFront.serverURL, actItem.appId,
                        actItem.ownKeyStorePath, "json", "GBK", actItem.oppCertFilePath, "RSA2");
                AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
                PayDetail detail = new PayDetail();
                detail.out_biz_no = p_req1908.singleDetail.askNumber;
                //16为纯数字
//                支付宝账号对应的支付宝唯一用户号,以2088开头的16位纯数字组成。
                if (p_req1908.singleDetail.payAct.matches("[0-9]{16}") &&
                        p_req1908.singleDetail.payAct.startsWith("2088")) {
                    detail.payee_type = "ALIPAY_USERID";
                } else {
                    detail.payee_type = "ALIPAY_LOGONID";
                }

                detail.payee_account = p_req1908.singleDetail.recAct;
                detail.amount = p_req1908.singleDetail.payAmount;
                detail.payer_show_name = p_req1908.singleDetail.payName;
                detail.payee_real_name = p_req1908.singleDetail.recName;
                detail.remark = p_req1908.singleDetail.purpose;
                request.setBizContent(JSON.toJSONString(detail));
                WriteBankLogStep2(JSON.toJSONString(detail));
                AlipayFundTransToaccountTransferResponse response = alipayClient.execute(request);
                if (response.isSuccess()) {
                    retAtsSglDetail.respCode = "0";
                    retAtsSglDetail.respInfo = response.getMsg();
                    retAtsSglDetail.reqSeqID = response.getOutBizNo();
                    retAtsSglDetail.transState = response.getCode();
                    retAtsSglDetail.payInfoCode = response.getSubCode();
                } else {
                    retAtsSglDetail.respCode = "0";
                    retAtsSglDetail.respInfo = response.getSubMsg();
                    retAtsSglDetail.reqSeqID = response.getOutBizNo();
                    retAtsSglDetail.transState = response.getCode();
                    retAtsSglDetail.payInfoCode = response.getSubCode();
                }
            } else {
                retAtsSglDetail.respCode = "-1";
                retAtsSglDetail.respInfo = "未找到账号[" + p_req1908.singleDetail.payAct + "]商户配置信息!";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAtsSglDetail.respCode = "-1";
            retAtsSglDetail.respInfo = ex.getMessage();
        }
        return retAtsSglDetail;
    }


    /**
     * AliPayClient构造函数参数，适用于公钥证书模式
     *
     * @param actItem
     * @return
     */
    private CertAlipayRequest getCertAlipayRequest(ActSetItem actItem) {
        CertAlipayRequest certAlipayRequest = new com.alipay.api.CertAlipayRequest();
        certAlipayRequest.setServerUrl(bankFront.serverURL);
        certAlipayRequest.setAppId(actItem.appId);
        certAlipayRequest.setPrivateKey(actItem.ownKeyStorePath);                   //商户私钥
        certAlipayRequest.setFormat("json");
        certAlipayRequest.setCharset(getBankConfig().getCharset("utf-8"));
        certAlipayRequest.setSignType(actItem.signType);
        certAlipayRequest.setCertPath(actItem.oppCertFilePath);                     //开发者应用公钥证书路径
        certAlipayRequest.setAlipayPublicCertPath(actItem.alipayPublicCertPath);    //支付宝公钥证书文件路径
        certAlipayRequest.setRootCertPath(actItem.rootCertPath);                    //支付宝CA根证书文件路径
        return certAlipayRequest;
    }

    /**
     * https://opendocs.alipay.com/apis/api_28/alipay.fund.trans.uni.transfer/
     *
     * @param p_req1908
     * @return
     */
    public RetAtsSglDetail d_190802(ReqSingle p_req1908) {
        RetAtsSglDetail retAtsSglDetail = new RetAtsSglDetail(p_req1908);
        try {
            ActSetItem actItem = getBankConfig().getActSetItemByAny(p_req1908.singleDetail.payAct, "", "", "singlePay");
            if (actItem != null) {
                String signType = "RSA2";
                boolean useSignType = getBankConfig().getValueAsBool("useSignType");
                if (useSignType) {
                    signType = actItem.signType;
                }
                AlipayClient alipayClient = new DefaultAlipayClient(bankFront.serverURL, actItem.appId, actItem.ownKeyStorePath, "json", "utf-8", actItem.oppCertFilePath, signType);
                AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
//                request.putOtherTextParam("ws_service_url", "bizfundprod-eu126-28.gz00b.dev.alipay.net:12200");
                Detail190802 detail = new Detail190802();
                PayeeInfo payeeInfo = new PayeeInfo();
                BankCardExtinfo bkCardExtInfo = new BankCardExtinfo();
                payeeInfo.identity = p_req1908.singleDetail.recAct;
                String sameBnk = p_req1908.singleDetail.sameBnk;
                //16为纯数字
//                支付宝账号对应的支付宝唯一用户号,以2088开头的16位纯数字组成。
                if (p_req1908.singleDetail.recAct.matches("[0-9]{16}") && p_req1908.singleDetail.recAct.startsWith("2088")) {
                    payeeInfo.identity_type = "ALIPAY_USER_ID";
                } else if ("1".equals(sameBnk)) {
                    payeeInfo.identity_type = "ALIPAY_LOGON_ID";
                    payeeInfo.name = p_req1908.singleDetail.recName;
                } else {
                    payeeInfo.identity_type = "BANKCARD_ACCOUNT";
                    payeeInfo.name = p_req1908.singleDetail.recName;
                    bkCardExtInfo.inst_name = p_req1908.singleDetail.recBankLocation;
                    bkCardExtInfo.inst_province = p_req1908.singleDetail.recAreaName.split("_")[0];
                    bkCardExtInfo.inst_city = p_req1908.singleDetail.recAreaName.split("_")[1];
                    bkCardExtInfo.inst_branch_name = p_req1908.singleDetail.recBankLocation;
                    bkCardExtInfo.bank_code = p_req1908.singleDetail.cnapsCode;
                    String isPrivate = p_req1908.singleDetail.isPrivate;
                    if ("1".equals(isPrivate)) {
                        bkCardExtInfo.account_type = "2";
                    } else {
                        bkCardExtInfo.account_type = "1";
                    }
                    detail.payee_info.bankcard_ext_info = bkCardExtInfo;
                }
                detail.out_biz_no = p_req1908.singleDetail.askNumber;
                detail.trans_amount = p_req1908.singleDetail.payAmount;
                if ("1".equals(sameBnk)) {
                    detail.product_code = "TRANS_ACCOUNT_NO_PWD";
                } else {
                    detail.product_code = "TRANS_BANKCARD_NO_PWD";
                }
                detail.biz_scene = "DIRECT_TRANSFER";
                detail.order_title = p_req1908.singleDetail.purpose;
                detail.remark = p_req1908.singleDetail.purpose;
                detail.payee_info = payeeInfo;
                request.setBizContent(JSON.toJSONString(detail));
                WriteBankLogLn2("提交银行的地址：" + bankFront.serverURL);
                WriteBankLogStep2(JSON.toJSONString(detail));
                AlipayFundTransUniTransferResponse response = alipayClient.execute(request);
                WriteBankLogStep3(response.getBody());
                retAtsSglDetail.respCode = "0";
                retAtsSglDetail.respInfo = response.getMsg();
                retAtsSglDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                if ("Success".equals(response.getMsg()) && "10000".equals(response.getCode())) {
                    //接口调用成功
                    retAtsSglDetail.transState = response.getStatus();
                    retAtsSglDetail.payInfoCode = retAtsSglDetail.transState;
                } else {
                    //接口调用异常，置为处理中，调用接口查询接口查询结果
                    retAtsSglDetail.transState = response.getSubCode();
                    retAtsSglDetail.payInfoCode = retAtsSglDetail.transState;
                    retAtsSglDetail.respInfo = response.getSubMsg();
                }
            } else {
                retAtsSglDetail.respCode = "-1";
                retAtsSglDetail.respInfo = "未找到账号[" + p_req1908.singleDetail.payAct + "]商户配置信息!";
            }
        } catch (Exception e) {
            e.printStackTrace();
            retAtsSglDetail.respCode = "0";
            retAtsSglDetail.respInfo = e.getMessage();
            WriteBankLogLn(e);
        }
        return retAtsSglDetail;
    }

    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail retAtsSglDetail = new RetAtsSglDetail();
        if ("190802".equals(p_req1944.reqHeader.commandCode)) {
            retAtsSglDetail = d_190802_singlePayQuery(p_req1944);
        } else {
            retAtsSglDetail = d_1908_singlePayQuery(p_req1944);
        }
        retAts.writeRetDetail(retAtsSglDetail);
        return retAts;
    }

    private RetAtsSglDetail d_1908_singlePayQuery(ReqQrySingle p_req1944) {
        RetAtsSglDetail retAtsSglDetail = new RetAtsSglDetail();
        try {
            ActSetItem actItem = getBankConfig().getActSetItemByAny(p_req1944.payAct, "", "", "singlePay");
            if (actItem != null) {
                AlipayClient alipayClient = new DefaultAlipayClient(bankFront.serverURL, actItem.appId,
                        actItem.ownKeyStorePath, "json", "GBK", actItem.oppCertFilePath, "RSA2");
                AlipayFundTransOrderQueryRequest request = new AlipayFundTransOrderQueryRequest();
                request.setBizContent("{" +
                        "\"out_biz_no\":\"" + p_req1944.askNumber + "\"," +
                        "\"order_id\":\"\"" +
                        "  }");
                AlipayFundTransOrderQueryResponse response = alipayClient.execute(request);
                if (response.isSuccess()) {
                    String err_code = response.getErrorCode();
                    if (StringHelper.isNullOrEmpty(err_code)) {
                        retAtsSglDetail.respCode = "0";
                        retAtsSglDetail.reqSeqID = response.getOutBizNo();
                        retAtsSglDetail.transState = response.getStatus();
                        retAtsSglDetail.payInfoCode = retAtsSglDetail.transState;
                    } else {
                        retAtsSglDetail.respCode = "-1";
                        retAtsSglDetail.respInfo = "查询失败：" + err_code;
                    }
                } else {
                    retAtsSglDetail.respCode = "-1";
                    retAtsSglDetail.respInfo = response.getSubMsg();
                }
            } else {
                retAtsSglDetail.respCode = "-1";
                retAtsSglDetail.respInfo = "未找到账号[" + p_req1944.payAct + "]商户配置信息!";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAtsSglDetail.respCode = "-1";
            retAtsSglDetail.respInfo = ex.getMessage();
        }
        return retAtsSglDetail;
    }

    /**
     * https://opendocs.alipay.com/apis/api_28/alipay.fund.trans.common.query/
     *
     * @param p_req1944
     * @return
     */
    private RetAtsSglDetail d_190802_singlePayQuery(ReqQrySingle p_req1944) {
        RetAtsSglDetail retAtsSglDetail = new RetAtsSglDetail(p_req1944);

        try {
            ActSetItem actItem = getBankConfig().getActSetItemByAny(p_req1944.payAct, "", "", "singlePay");
//            ActSetItem actItem = getBankConfig().getActSetItemByAny(p_req1944.payAct, "", "", "singlepay");
            if (actItem != null) {
                String signType = "RSA2";
                boolean useSignType = getBankConfig().getValueAsBool("useSignType");
                if (useSignType) {
                    signType = actItem.signType;
                }
                AlipayClient alipayClient = new DefaultAlipayClient(bankFront.serverURL, actItem.appId, actItem.ownKeyStorePath, "json", "utf-8", actItem.oppCertFilePath, signType);
                AlipayFundTransCommonQueryRequest request = new AlipayFundTransCommonQueryRequest();
//                request.putOtherTextParam("ws_service_url", "bizfundprod-eu126-28.gz00b.dev.alipay.net:12200");
                SingleQueryDetail singleQueryDetail = new SingleQueryDetail();
                String sameBnk = p_req1944.sameBnk;
                if ("1".equals(sameBnk)) {
                    singleQueryDetail.product_code = "TRANS_ACCOUNT_NO_PWD";
                } else {
                    singleQueryDetail.product_code = "TRANS_BANKCARD_NO_PWD";
                }
                singleQueryDetail.biz_scene = "DIRECT_TRANSFER";
                singleQueryDetail.out_biz_no = p_req1944.askNumber;
                String bizContent = JSON.toJSONString(singleQueryDetail);
                request.setBizContent(bizContent);
                WriteBankLogLn2("提交银行的地址：" + bankFront.serverURL);
                WriteBankLogStep2(bizContent);
                AlipayFundTransCommonQueryResponse response = alipayClient.execute(request);
                WriteBankLogStep3(response.getBody());
                String err_code = response.getErrorCode();
                retAtsSglDetail.respCode = "0";
                if ("Success".equals(response.getMsg()) && "10000".equals(response.getCode())) {
                    //接口调用成功
                    retAtsSglDetail.respInfo = response.getMsg();
                    if("FAIL".equals(response.getStatus())||"REFUND".equals(response.getStatus())){
                        retAtsSglDetail.transState = response.getStatus();
                        retAtsSglDetail.payInfoCode = response.getErrorCode();
                        retAtsSglDetail.respInfo = response.getFailReason();
                    }else{
                        retAtsSglDetail.transState = response.getStatus();
                        retAtsSglDetail.payInfoCode = retAtsSglDetail.transState;
                    }
                    retAtsSglDetail.transAmt = response.getTransAmount();
                } else {
                    //接口调用失败
                    retAtsSglDetail.respInfo = response.getSubMsg();
                    String sub_code = response.getSubCode();
                    if("ORDER_NOT_EXIST".equals(sub_code)){
                        if(canBeNotExist(p_req1944,retAtsSglDetail,30)){
                            retAtsSglDetail.transState = sub_code;
                            retAtsSglDetail.payInfoCode = sub_code;
                        }
                    }else{
                        retAtsSglDetail.transState = sub_code;
                        retAtsSglDetail.payInfoCode = sub_code;
                    }
                }
            } else {
                retAtsSglDetail.reqSeqID = p_req1944.askNumber;
                retAtsSglDetail.respCode = "-1";
                retAtsSglDetail.respInfo = "未找到账号[" + p_req1944.payAct + "]商户配置信息!";
            }
        } catch (Exception e) {
            e.printStackTrace();
            retAtsSglDetail.reqSeqID = p_req1944.askNumber;
            retAtsSglDetail.respCode = "-1";
            retAtsSglDetail.respInfo = e.getMessage();
            WriteBankLogLn(e);
        }
        return retAtsSglDetail;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
